package cn.maxwell.user.service.impl;

import cn.maxwell.basic.constant.VerifyCodeConstants;
import cn.maxwell.basic.service.impl.BaseServiceImpl;
import cn.maxwell.basic.util.BusinessException;
import cn.maxwell.basic.util.Md5Utils;
import cn.maxwell.basic.util.StrUtils;
import cn.maxwell.user.domain.Logininfo;
import cn.maxwell.user.domain.User;
import cn.maxwell.user.dto.UserDto;
import cn.maxwell.user.mapper.LogininfoMapper;
import cn.maxwell.user.mapper.UserMapper;
import cn.maxwell.user.service.IUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

@Service
public class UserServiceImpl extends BaseServiceImpl<User> implements IUserService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private LogininfoMapper logininfoMapper;

    @Transactional
    @Override
    public void phoneRegister(UserDto userDto) {
        String username = userDto.getUsername();
        String phone = userDto.getPhone();
        String phoneCode = userDto.getPhoneCode();
        String password = userDto.getPassword();
        String  RepeatPwd = userDto.getPasswordRepeat();
        //1.校验
        //1.1空值校验
        if(StringUtils.isEmpty(username)
                || StringUtils.isEmpty(phone)
                || StringUtils.isEmpty(phoneCode)
                || StringUtils.isEmpty(password)
                || StringUtils.isEmpty(RepeatPwd)){
            throw new BusinessException("数据不能为空!!!");
        }
        //1.2两次密码是否相同
        if(!password.equals(RepeatPwd)){
            throw new BusinessException("两次密码不一致!!!");
        }
        //1.3判断用户名是否被占用：要保证用户名唯一
        //获取数据库里面的用户名，可以直接用logininfo表拿值  dbUsername:代表根据用户名查询到的数据==>如果在数据库里面可以查询到信息说明改名称已被注册过
        Logininfo dbUsername = logininfoMapper.loadByUsername(username);
        if(dbUsername != null){
            throw new BusinessException("该用户名被占用，请重新输入");
        }
        //1.4验证码是否过期
        Object obj = redisTemplate.opsForValue().get(VerifyCodeConstants.REGISTER_CODE_PREFIX + phone);
        if(obj == null){
            throw new BusinessException("验证码无效，请重新获取!!!");
        }
        //1.5验证码是否正确  //  9527:1223555555
        String codeTmp = obj.toString().split(":")[0];
        if(!codeTmp.equalsIgnoreCase(phoneCode)){
            throw new BusinessException("验证码错误!!!");
        }

        //2.保存数据
        //2.1.先保存t_logininfo
        User user = userDto2User(userDto);
        Logininfo logininfo = user2Logininfo(user);

        logininfoMapper.add(logininfo);//自增
        //2.2.再保存t_user 这个logininfo要保存上面通过方法获取的user
        //这句话的意思是获取user表的logininfo_id字段信息
        user.setLogininfo_id(logininfo.getId());
        //user.setLogininfo(logininfo);
        userMapper.add(user);
    }

    private User userDto2User(UserDto userDto) {
        User user = new User();
        user.setUsername(userDto.getUsername());
        user.setPhone(userDto.getPhone());
        //获取随机盐值
        String salt = StrUtils.getComplexRandomString(32);
        //获取加密之后的密码
        String md5Pwd = Md5Utils.encrypByMd5(userDto.getPassword()+salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);
        return user;
    }

    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        //按照同名属性赋值【username，email，phone，salt，password】
        BeanUtils.copyProperties(user,logininfo);
        //当前对象是用户 1代表用户  0代表员工
        logininfo.setType(1);
        return logininfo;
    }

    /**
     * 添加操作：其他没有添加的字段是因为页面在修改时会重新赋值
     * @param user
     */
    @Transactional
    @Override
    public void add(User user) {
        //1.处理密码和盐值
        //获取随机盐值
        String salt = StrUtils.getComplexRandomString(32);
        //获取加密之后的密码
        String md5Pwd = Md5Utils.encrypByMd5(user.getPassword()+salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);

        Logininfo logininfo = user2Logininfo(user);
        logininfoMapper.add(logininfo);
        userMapper.add(user);
    }

    /**
     * 修改操作：其他没有添加的字段是因为页面在修改时会重新赋值
     * @param user
     */
    @Transactional
    @Override
    public void update(User user){
        //盐值
        String salt = StrUtils.getComplexRandomString(32);
        //密码
        String password = user.getPassword();
        String md5Password = Md5Utils.encrypByMd5(password + salt);
        user.setSalt(salt);
        user.setPassword(md5Password);
        //保存
        //获取登录信息id
        Long logininfo_id = userMapper.loadById(user.getId()).getLogininfo_id();
        //登录信息logininfo：type不修改
        Logininfo logininfo = user2Logininfo(user);//再次调用方法获取信息
        //设置logininfo表的id，因为id是自增的，我们是修改操作不应该改变id
        logininfo.setId(logininfo_id);
        //更新修改到数据库
        logininfoMapper.update(logininfo);
        //更新user表
        userMapper.add(user);
    }

    /**
     * 删除操作
     * @param id
     */
    @Transactional
    @Override
    public void delete(Long id){

        //删除logininfo登录信息
        //获取登录信息id
        Long logininfo_id = userMapper.loadById(id).getLogininfo_id();
        logininfoMapper.delete(logininfo_id);
        //删除user表信息
        userMapper.delete(id);
    }
}